package com.example.utils;

import com.example.constants.Constants;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

// 命令下发
public class ProductCommandIssued {

    public static void issueCommand(String commandName, String serviceId, Map<String, Object> paras, String token) throws Exception {
        String result = issueCommandByToken(Constants.PROJECT_ID, Constants.DEVICE_ID,
                commandName,
                serviceId,
                paras,
                token);
        System.out.println(result);
    }

    public static String issueCommandByToken(String projectId, String deviceId, String commandName, String serviceId, Map<String, Object> parasMap, String token) throws Exception {
        String url = String.format(Constants.ISSUE_COMMAND_URL, projectId, deviceId);// 目标地址
        // 构造请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("X-Auth-Token", token);

        // JSON请求体动态组装
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode body = mapper.createObjectNode();
        body.put("command_name", commandName);  // 命令名称
        body.put("service_id", serviceId);  // 服务id
        ObjectNode parasNode = mapper.createObjectNode();
        for (Map.Entry<String, Object> entry : parasMap.entrySet()) {
            Object value = entry.getValue();
            // 针对不同数据类型采取不同格式化策略
            if (value instanceof Number) {
                parasNode.put(entry.getKey(), ((Number) value).doubleValue());
            } else if (value instanceof Boolean) {
                parasNode.put(entry.getKey(), (Boolean) value);
            } else {
                parasNode.put(entry.getKey(), value.toString());
            }
        }
        body.set("paras", parasNode);   // 命令内容
        String jsonBody = body.toString();

        // 发送 POST 请求
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS) // 设置连接超时
                .readTimeout(20, TimeUnit.SECONDS)    // 设置读取超时
                .build();
        // 构建请求体(JSON格式)
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonBody);
        Request.Builder builder = new Request.Builder()
                .url(url)   // 设置目标API地址
                .post(requestBody); // 指定POST方法并附加请求体
        for (Map.Entry<String, String> entry : headers.entrySet()) {// 动态添加请求头
            builder.addHeader(entry.getKey(), entry.getValue());
        }
        // 响应处理
        try (Response response = client.newCall(builder.build()).execute()) {
            if (response.body() != null) {
                String responseBody = response.body().string(); // 获取响应体文本
                //如果返回错误码,判断是否是令牌过期的原因
                IsValidToken.isValidToken(responseBody);

                return response.body().string(); // 返回响应体文本
            } else {
                return "No response body";  // 无响应
            }
        }
    }
}
